import { createStore, clear, setMany, getMany } from "idb-keyval";

const store = createStore("current_user_db", "current_user_store");

async function clearUserInfo() {
  return await clear(store);
}

async function setToken({ token, expiration }) {
  return await setMany(
    [
      ["token", token],
      ["expiration", expiration],
    ],
    store
  );
}

async function isAuthorized() {
  const [token, expiration] = await getMany(["token", "expiration"], store);

  if (!token) {
    return false;
  }

  return new Date().getTime() < expiration;
}

async function acquireToken() {
  const [token, expiration] = await getMany(["token", "expiration"], store);
  if (!token) {
    throw new Error("请先登录");
  } else if (new Date().getTime() >= expiration) {
    throw new Error("会话超时，请注销后重新登录");
  }
  return `Bearer ${token}`;
}

export { clearUserInfo as clear, setToken, isAuthorized, acquireToken };
